let userMethod = require("../dao/userListDAO").userMethod;

// 注册用户
exports.register = function (req, res){
  userMethod.findOne({userName:req.body.userName}, function (err, doc){
    if(!err){
      if(!doc){
        let newUser = {userName: req.body.userName, passWord: req.body.passWord};
        userMethod.save(newUser, function (err){
          if(!err){
            res.send({
              code: 200,
              msg: "注册成功！"
            });
          }
        });
      }else{
        res.send({
          code: 201,
          msg: "用户名已被占用！"
        });
      }
    }
  });
};

// 登录
exports.login = function (req, res){
  userMethod.findOne({userName:req.body.userName}, function (err, doc){
    if(!err && doc && req.body.passWord === doc.passWord){
      res.send({
        code: 200,
        data: doc,
        msg: "登录成功！"});
    }else{
      res.send({code:201, msg:"用户名或密码错误！"});
    }
  });
};

// 获取用户列表
exports.getUserList = function (req, res){
  // 根据用户id查询列表
  userMethod.findAll(function (err, doc) {
    if(!err){
      res.send({
        code: 200,
        data: doc,
        msg: "查询成功！"});
    }
    else{
      res.send({
        code: 201,
        msg: "查询失败！"});
    }
  })
};

// 删除
exports.delUser = function (req, res){
  let id = req.body.id
  console.log(id)
  // 根据id查询单条数据
  userMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      let par = {
        _id: id
      }
      // 删除单条数据
      userMethod.remove(par,function (err, doc) {
        if(!err){
          res.send({
            code: 200,
            msg: "删除成功！"});
        }else{
          res.send({
            code: 200,
            msg: "删除失败！"});
        }
      })
    }
  })
};

// 修改
exports.editUser = function (req, res) {
  let newUser = {
  };
  // 查询单个数据
  userMethod.findOneById(newUser.id,function (err, doc) {
    if(!err && doc){
      // 更新单个数据
      userMethod.update({'_id':newUser.id},newUser,function (err) {
        if(!err){
          res.send({
            code: 200,
            msg: "修改成功！"});
        }
        else{
          res.send({
            code: 201,
            msg: "修改失败！"});
        }
      })
    }
  })
}
